// utils/keyboardManager.ts
import { useAppStore } from '@/stores/appStore'
import { ShortcutConfig, loadUserShortcuts } from '@/config/shortcuts'

export class KeyboardManager {
  private static instance: KeyboardManager
  private shortcuts: Map<string, () => void> = new Map()
  private store: ReturnType<typeof useAppStore> | null = null
  private shortcutConfig: ShortcutConfig[] = []

  private constructor() {
    this.init()
  }

  public static getInstance(): KeyboardManager {
    if (!KeyboardManager.instance) {
      KeyboardManager.instance = new KeyboardManager()
    }
    return KeyboardManager.instance
  }

  private getStore() {
    if (!this.store) {
      this.store = useAppStore()
    }
    return this.store
  }

  private init() {
    // 加载快捷键配置
    this.loadConfig()
    
    // 绑定全局键盘事件
    document.addEventListener('keydown', this.handleKeyDown.bind(this))
    
    // 注册默认快捷键
    this.registerDefaultShortcuts()
  }

  // 加载快捷键配置
  public loadConfig() {
    this.shortcutConfig = loadUserShortcuts()
  }

  // 获取快捷键配置
  public getConfig(): ShortcutConfig[] {
    return this.shortcutConfig
  }

  // 更新快捷键配置
  public updateConfig(config: ShortcutConfig[]) {
    this.shortcutConfig = config
    // 重新注册快捷键
    this.unregisterAllShortcuts()
    this.registerDefaultShortcuts()
  }

  private handleKeyDown(event: KeyboardEvent) {
    // 忽略在输入框中的快捷键
    if (this.isInputEvent(event)) {
      return
    }

    const key = this.getShortcutKey(event)
    if (this.shortcuts.has(key)) {
      event.preventDefault()
      this.shortcuts.get(key)!()
    }
  }

  private isInputEvent(event: KeyboardEvent): boolean {
    const target = event.target as HTMLElement
    return (
      target.tagName === 'INPUT' ||
      target.tagName === 'TEXTAREA' ||
      target.contentEditable === 'true'
    )
  }

  private getShortcutKey(event: KeyboardEvent): string {
    const keys = []
    
    if (event.ctrlKey || event.metaKey) keys.push('Ctrl')
    if (event.altKey) keys.push('Alt')
    if (event.shiftKey) keys.push('Shift')
    
    // 处理功能键
    if (event.key.startsWith('F') && event.key.length > 1) {
      keys.push(event.key)
    } else {
      // 处理字母和数字键
      const key = event.key.length === 1 ? event.key.toUpperCase() : event.key
      keys.push(key)
    }
    
    return keys.join('+')
  }

  public registerShortcut(key: string, callback: () => void) {
    this.shortcuts.set(key, callback)
  }

  public unregisterShortcut(key: string) {
    this.shortcuts.delete(key)
  }

  private unregisterAllShortcuts() {
    this.shortcuts.clear()
  }

  private registerDefaultShortcuts() {
    this.shortcutConfig.forEach(config => {
      if (config.enabled) {
        switch (config.action) {
          case 'reload':
            this.registerShortcut(config.key, () => {
              window.location.reload()
            })
            break
          case 'toggleTheme':
            this.registerShortcut(config.key, () => {
              const store = this.getStore()
              store.toggleTheme()
            })
            break
          case 'toggleSidebar':
            this.registerShortcut(config.key, () => {
              const store = this.getStore()
              store.toggleSidebar()
            })
            break
          default:
            // 默认处理路由跳转
            if (config.action.startsWith('#/')) {
              this.registerShortcut(config.key, () => {
                window.location.hash = config.action
              })
            }
            break
        }
      }
    })
  }
}

// 创建全局实例
export const keyboardManager = KeyboardManager.getInstance()